package nillon.demo4.model;

import java.sql.*;

public class DBTest {

    public String name;
    public String pass;

    public void sendInfo(String username, String passwoed) {
        this.name=username;
        this.pass=passwoed;
    }

    public String userlogin() {
        String url = "jdbc:mysql://localhost:3306/library_management?useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true";
        String username = "root"; // 你的数据库用户名
        String password = "07162007lyr"; // 你的数据库密码
        String sql ="select *from user where username = ? and password = ?";
        String nameChecked = null;


        Connection conn=null;
        PreparedStatement prep=null;
        ResultSet rs =null;

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn= DriverManager.getConnection(url, username, password);

            prep = conn.prepareStatement(sql);
            prep.setString(1, name);
            prep.setString(2, pass);
            rs = prep.executeQuery();

            while (rs.next()) {
                nameChecked = rs.getString("name");

            }

            if (nameChecked!=null) {
                return nameChecked;
            }else  {
                return null;
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                rs.close();
            } catch (SQLException e) {
                System.out.println("rs failed");
                e.printStackTrace();
            }
            try {
                prep.close();
            } catch (SQLException e) {
                System.out.println("prep.failed");
                e.printStackTrace();
            }
            try {
                conn.close();
            } catch (SQLException e) {
                System.out.println("conn failed");
                e.printStackTrace();
            }
        }
        return null;
    }
}
